<?php

namespace App\Task\Stat;

use App\Model\CoinLog;
use App\Model\Gift;
use App\Model\GiftLog;
use App\Model\Stat\StatDailySysGift;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * 每日名义礼物统计
 * @Crontab(name="StatDailySysGiftTask", rule="25,50 *\/1 * * *", callback="execute", memo="每日名义礼物统计", singleton=false)
 */
class StatDailySysGiftTask
{
    /**
     * @return void
     */
    public function execute()
    {
        log_info(__CLASS__ . "==Start==" . date('Y-m-d H:i:s'));
        $this->dt = date('Y-m-d');
        $nextDay = -1;
        $this->endTime = date('Y-m-d', strtotime("-{$nextDay} day"));
        $giftIds = Gift::getSysGiftIds();
        $giftIds[] = 0;
        foreach ($giftIds as $giftId) $this->beginStat($giftId);
    }

    /**
     * 获取模型
     */
    function getModel($statClass, $giftId = 0)
    {
        $where = ['dt' => $this->dt, 'gift_id' => $giftId];
        $model = $statClass::where($where)->first();
        if (!$model) $model = new $statClass();
        return $model;
    }

    /**
     * 日报-名义礼物
     */
    function beginStat($giftId = 0)
    {
        $model = $this->getModel(StatDailySysGift::class, $giftId);
        if (!$model) return false;
        $model->dt = $this->dt;
        $model->send_num = GiftLog::getSysCount($this->dt, $this->endTime, -1, 'count', $giftId);
        $model->receive_num = GiftLog::getSysCount($this->dt, $this->endTime, GiftLog::STATUS_OK, 'count', $giftId);
        $model->send_from_num = GiftLog::getSysCount($this->dt, $this->endTime, -1, 'send_user', $giftId);
        $model->send_to_num = GiftLog::getSysCount($this->dt, $this->endTime, -1, 'receive_user', $giftId);
        $model->receive_user_num = GiftLog::getSysCount($this->dt, $this->endTime, GiftLog::STATUS_OK, 'receive_user', $giftId);
        $model->receive_gift_coin = GiftLog::getSysCount($this->dt, $this->endTime, GiftLog::STATUS_OK, 'coin', $giftId);
        $model->actual_income_coin = round(CoinLog::getSysGiftCoin($this->dt, $this->endTime), 1);
        $model->gift_id = $giftId;
        log_info(__METHOD__ . "==" . json_encode($model));
        $model->saveOrFail();
        return;
    }
}
